//
//  setUpFaceIDViewController.m
//  dongfengTest
//
//  Created by wxt on 2021/3/18.
//

#import "SetUpFaceIDViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "LognViewController.h"
@interface SetUpFaceIDViewController ()
@property (retain,nonatomic) LAContext *faceIDContext;
@property (assign,nonatomic) NSInteger BiometryTypeNumber;
@property (strong,nonatomic) NSString * BiometryTypeStr;
@property (strong,nonatomic)UISwitch* openbutton;
@end

@implementation SetUpFaceIDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = JhColor(246, 246, 246);
    
    UIButton * backBtn =[UIButton createBtnFrame:CGRectMake(15, kStatusBarHeight+5, 18, 18) title:@"" bgImageName:@"fanhui" action:^(UIButton *button) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [self.view addSubview:backBtn];
    TKLlable * navTit = [TKLlable labelWithFrame:CGRectMake(kWidth/2-60, kStatusBarHeight+5, 120, 20) text:@"" textColor:Bcolor font:Font_6(16) textAlignment:Textcenter backgroundColor:Ccolor];
    [self.view addSubview:navTit];

        navTit.text= @"生物识别验证";

    
    [self isSupportBiometrics];
    [self addUIView];
    // Do any additional setup after loading the view.

    // Do any additional setup after loading the view.
}
-(void)addUIView{
    
    UIView * bgview = [[UIView alloc]initWithFrame:CGRectMake(0, kTopHeight+20, kWidth, 50)];
    bgview.backgroundColor = Wcolor;
    [self.view addSubview:bgview];
    
    TKLlable * IDlab = [TKLlable labelWithFrame:CGRectMake(20, 15, 120, 20) text:@"" textColor:Bcolor font:Font_6(14) textAlignment:Textleft backgroundColor:Ccolor];
    [bgview addSubview:IDlab];
    
    self.openbutton = [[UISwitch alloc]initWithFrame:CGRectMake(kWidth-70, 10, 100, 20)];
    
//    [self queryOpenBiorm];
    

//
    
    
        // 添加事件
        [self.openbutton addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];   // 开关事件切换通知
        [bgview addSubview:self.openbutton];
 
    [self.openbutton setOnTintColor:JhColor(147, 149, 174)];
    [self.openbutton setTintColor:JhColor(230, 230, 230)];

        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
        NSString * isBio = [stand objectForKey:@"bio"];
        if ([isBio isEqualToString:@"1"]) {
            self.openbutton.on=YES;
        }else{
            self.openbutton.on=NO;
        }
    
    
    //判断支持哪一种
    if (self.BiometryTypeNumber ==1) {
        ;
        IDlab.text = @"开启指纹识别";
    }else if(self.BiometryTypeNumber ==2){
        IDlab.text = @"开启面容识别";
    }else{
        
        IDlab.text = @"";
    }
    
}


-(void)switchChange:(id)sender{
    
    
    if (self.BiometryTypeNumber == 0) {
        [MBProgressHUD showError:@"设备暂未开启该权限,请前往设置中开启" toView:self.view];;
    }else{
        UISwitch* openbutton = (UISwitch*)sender;
        Boolean ison = openbutton.isOn;
         if(ison){
             

             [self openBiomerAction:1];
             
             
         }else{
             [self openBiomerAction:0];

             
         }
        
    }
    
    
 
}

-(void)openBiomerAction:(int)num{
   

     
        
        NSString *localizedReason = [NSString stringWithFormat:@"%@识别",self.BiometryTypeStr];
        [self.faceIDContext evaluatePolicy:(LAPolicyDeviceOwnerAuthentication) localizedReason:localizedReason reply:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                

                NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];

                NSError *keychainError = [QiKeychainItem queryKeychainWithService:QikeychainService account:   @"userUUID"];

                if (keychainError.code == errSecSuccess) {
                    
                    [NetRequestClass NetRequestPOSTWithRequestURL:kUser_UserDevice_Api WithParameter:@{@"deviceId":[keychainError.userInfo valueForKey:NSLocalizedDescriptionKey],@"uno":[stand objectForKey:@"userName"],@"fpSwitch":@(num)} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
                        NSLog(@"%@",returnValue);
                        if ([returnValue[@"code"] intValue] == 200) {
                            
                            NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
                            [MBProgressHUD showMessage:@"设置成功" toView:self.view];
                            
                            if (num == 0) {
                                [stand setObject:@"0" forKey:@"bio"];
                                self.openbutton.on = NO;
                                
                            }else{
                                [stand setObject:@"1" forKey:@"bio"];
                                self.openbutton.on = YES;
                            }
                           
                        }else if ([returnValue[@"code"] intValue] == 401) {
                            //token过期
                            LognViewController * viewVC = [[LognViewController alloc]init];
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"tokenNotime" object:@""];
                            [UIApplication sharedApplication].keyWindow.rootViewController = viewVC;
                          
                        }else{
                            
                       
                            
                            
//                            [stand setObject:@"0" forKey:@"bio"];
//                            [MBProgressHUD showMessage:@"失败" toView:self.view];
//                            self.openbutton.on = NO;
                        }
                        
                        
                        
                        
                    } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
                       NSLog(@"%@",error) ;
                    } WithFailureBlock:^{
                        ;
                    }];
                }
                
            }else{
                NSLog(@"check error --->%@",error.localizedDescription);
                [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                    
                    if (num == 0) {
                        self.openbutton.on = YES;
                    }else{
                        self.openbutton.on = NO;
                    }
                    
                }];
            
                switch (error.code) {
                    case LAErrorSystemCancel:
                    {
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            [MBProgressHUD showError:@"系统取消授权" toView:self.view];
                        }];
                    }
                        
                        break;
                    case LAErrorUserCancel:{
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            [MBProgressHUD showError:@"用户取消验证" toView:self.view];
                        }];
                    }
                        break;
                    case LAErrorAuthenticationFailed:
                
                    {
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            [MBProgressHUD showError:@"授权失败" toView:self.view];
                        }];
                    }
                        break;
                    case LAErrorPasscodeNotSet:
                    {
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            [MBProgressHUD showError:@"系统未设置密码" toView:self.view];
                        }];
                    }
                        break;
                    case LAErrorBiometryNotAvailable:
                    {
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            [MBProgressHUD showError:@"设备生物ID不可用" toView:self.view];
                        }];
                    }
                        
                        break;
                    case LAErrorBiometryNotEnrolled:
                    {
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            [MBProgressHUD showError:@"设备生物ID不可用，用户未登录" toView:self.view];
                        }];
                    }
                       
                        break;
                    case LAErrorUserFallback:{
                        
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            NSLog(@"用户选择输入密码，切换到主线程");                 ;
                        }];
                        
                    }
                        
                        break;
                    default:{
                        
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            NSLog(@"其他情况，切换到主线程");                 ;
                        }];
                        
                    }
                        break;
                }
                
            }
        }];

        
    }
    


-(void)isSupportBiometrics{
    
    
    self.BiometryTypeNumber = [BiomerTool isSupportBiometrics];
    if (self.BiometryTypeNumber == 1) {
        self.BiometryTypeStr = @"指纹";
    }else if(self.BiometryTypeNumber ==2){
        self.BiometryTypeStr = @"面部";
    }else{
        self.BiometryTypeStr = @"生物";
    }

    
}
- (LAContext *)faceIDContext{
    if (!_faceIDContext) {
        _faceIDContext = [[LAContext alloc] init];
    }
    return _faceIDContext;
}
-(void)dealloc{
  
    
        
        [[NSNotificationCenter defaultCenter] removeObserver:self];
 
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
